package com.luhuiguo.contacts.server.service.impl;

import java.util.Date;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.luhuiguo.contacts.server.service.ContactService;
import com.luhuiguo.contacts.shared.entity.Contact;

@Service
public class ContactServiceImpl implements ContactService {

    @PersistenceContext
    protected EntityManager em;

    @Override
    @Transactional
    public Contact createContact(Contact contact) {
        Date now = new Date();
        contact.setCreated(now);
        contact.setLastModified(now);
        em.persist(contact);
        return contact;
    }

    @Override
    @Transactional(readOnly = true)
    public Contact getContact(Long id) {
        return em.find(Contact.class, id);
    }

    @Override
    @Transactional
    public Contact updateContact(Contact contact) {
        Date now = new Date();
        contact.setLastModified(now);
        return em.merge(contact);
    }

    @Override
    @Transactional
    public void removeContact(Long id) {
        em.remove(getContact(id));

    }

    @SuppressWarnings("unchecked")
    @Override
    public List<Contact> findAllContact(int... rowStartIdxAndCount) {
        Query q = em.createQuery("from Contact");
        if (rowStartIdxAndCount != null && rowStartIdxAndCount.length > 0) {
            int rowStartIdx = Math.max(0, rowStartIdxAndCount[0]);
            if (rowStartIdx > 0) {
                q.setFirstResult(rowStartIdx);
            }
            if (rowStartIdxAndCount.length > 1) {
                int rowCount = Math.max(0, rowStartIdxAndCount[1]);
                if (rowCount > 0) {
                    q.setMaxResults(rowCount);
                }
            }
        }
        return q.getResultList();
    }

}
